package com.icare.common.service.utils;

import com.google.common.collect.Maps;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 描述:redis缓存工具类
 * 创建者:田海波 于 2018年05月31日 18:21.
 */
public class RedisCacheUtil {

    private static StringRedisTemplate redisTemplate;

    private static int liveTime = 60;

    public static void setRedisTemplate(StringRedisTemplate redisTemplate) {
        RedisCacheUtil.redisTemplate = redisTemplate;
    }

    public static void set(String key, String value){
        set(key,value,liveTime);
    }

    public static void set(String key, String value, int liveTime){
        redisTemplate.opsForValue().set(key,value,liveTime,TimeUnit.SECONDS);
    }

    public static void set(String key, Map<?,?> value, int liveTime){
        redisTemplate.opsForHash().putAll(key,value);
        redisTemplate.expire(key,liveTime,TimeUnit.SECONDS);
    }

    public static void set(Map<String ,Object> keyvalues){
        set(keyvalues,liveTime);
    }

    public static void set(Map<String ,Object> keyvalues, Integer liveTime){
        HashMap<String, String> map = Maps.newHashMap();
        keyvalues.keySet().stream().forEach(a -> map.put(a,keyvalues.get(a).toString()));
        redisTemplate.opsForValue().multiSet(map);
        keyvalues.keySet().stream().forEach(a -> redisTemplate.expire(a,liveTime,TimeUnit.SECONDS));
    }

    public static void del(String key){
        redisTemplate.delete(key);
    }

    public static void del(String...key){
        redisTemplate.delete(Arrays.asList(key));
    }

    public static String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public static List<String> get(String...key){
        return redisTemplate.opsForValue().multiGet(Arrays.asList(key));
    }

    public static Map<Object,Object> getHash(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    public static void put(String key,String hashKey,String value){
        redisTemplate.opsForHash().put(key,hashKey,value);
    }

    public static Boolean exists(String key){
        RedisCallback<Boolean> tRedisCallback = connection -> connection.exists(key.getBytes());
        return redisTemplate.execute(tRedisCallback);
    }

}
